#include <iostream>
#include "Socket.hpp"
#include "Protocol.hpp"
#include <unistd.h>
#include <sys/wait.h>
#include <sys/types.h>
#include <functional>

using func_t = std::function<std::string(std::string &package)>;

class TcpServer
{
public:
    TcpServer(uint16_t local_port, func_t cb)
        : port(local_port),
          callback_(cb)
    {
    }

public:
    bool initServer()
    {
        st.Socket();
        st.Bind(port);
        st.Listen();
        lg(INFO, "init Server done");
        return true;
    }
    void Start()
    {
        while (true)
        {
            std::string clientip;
            uint16_t clientport;
            int rwfd = st.Accept(&clientip, &clientport);
            if (rwfd == -1)
                continue;
            lg(INFO, "accept a new link, sockfd: %d, clientip: %s, clientport: %d", rwfd, clientip.c_str(), clientport);
            pid_t pid = fork();
            if (pid == 0)
            {
                // 子进程
                std::string inbuffer_stream; // 用于接受读过来的内容的
                while (true)
                {
                    st.Close();
                    char buffer[1280];
                    size_t n = read(rwfd, buffer, sizeof(buffer));
                    if (n > 0)
                    {
                        buffer[n] = '\0';
                        inbuffer_stream += buffer;

                        lg(INFO, "read a message is %s", buffer);
                        while (true)
                        {
                            std::string p = callback_(inbuffer_stream);
                            // std::cout << "server responce:" << p << std::endl;
                            if (p.empty() && n == 0) break;
                            write(rwfd, p.c_str(), p.size());
                            
                        }
                    }
                    else
                    {
                        lg(WARNING, "read failed %d:%s", errno, strerror(errno));
                        break;
                    }
                }
            }
            waitpid(pid, nullptr, 0);
        }
    }

private:
    uint16_t port;
    St st;
    func_t callback_;
};